package com.zyw.security.shiro.web.filter;

import com.zyw.utils.StringUtils;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author zhangyw
 * @date 2018/1/31 9:11
 */
public abstract class BasicAuthenticationFilter extends AuthenticationFilter {

    protected static final Logger log = LoggerFactory.getLogger(UserLoginAuthenticationFilter.class);

    static final String LOGIN_ERROR_KEY_ATTRIBUTE_NAME = "loginFailMsg";

    /**
     * 部分涉及需要跳转，带跳转的参数名
     */
    private static final String REDIRECT_PARAM = "redirect";

    protected String getRedirectUrl(ServletRequest request){
        return WebUtils.getCleanParam(request, REDIRECT_PARAM);
    }

    protected void saveRequestAndRedirectToSuccess(ServletRequest request, ServletResponse response) throws Exception {
        saveRequest(request);
        String redirect = getRedirectUrl(request);
        if (StringUtils.isNotEmpty(redirect) && !"/".equals(redirect)) {
            WebUtils.issueRedirect(request, response, redirect);
        } else {
            WebUtils.issueRedirect(request, response, getSuccessUrl());
        }
    }

    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        saveRequest(request);
        String loginUrl = getLoginUrl();
        if (!isLoginRequest(request, response)) {// 当不是登录页访问时，给访问url拼接跳转地址
            HttpServletRequest request1 = WebUtils.toHttp(request);
            String reqUrl = request1.getRequestURI();

            if (!reqUrl.equals("/") && !reqUrl.equals(request1.getContextPath())) {
                String queryStr = request1.getQueryString();

                if (queryStr != null) {
                    reqUrl = reqUrl + "?" + queryStr;
                }

                loginUrl = loginUrl + "?" + "redirect=" + URLEncoder.encode(reqUrl, "UTF-8");
            }
        }
        WebUtils.issueRedirect(request, response, loginUrl);
    }
}
